<?php

require_once __DIR__ . '/./const.php';

$params = getopt('e:');

$event = $params['e'] ?? '';

switch ($event) {
    case EventCreate:
        createIndex();
        break;
    case EventUpsertData:
        upsertData();
        break;
    case EventGetData:
        getData();
        break;
    default:
        echo errorMessage();
        exit;
}

function createIndex(): void
{
    $client = esClient();

    $params = [
        'index' => EsIndex,
        'body'  => [
            'settings' => [
                'number_of_shards'   => 3,
                'number_of_replicas' => 2
            ],
            'mappings' => [
                '_source'    => [
                    'enabled' => true
                ],
                'properties' => [
                    'car_name'  => [
                        'type' => 'text'
                    ],
                    'car_price' => [
                        'type' => 'float'
                    ]
                ]
            ]
        ]
    ];

    $response = $client->indices()->create($params);
    print_r($response);
}

function upsertData(): void
{
    $data   = file_get_contents(__DIR__ . '/../data/data.json');
    $params = json_decode($data, true);

    $client = esClient();
    foreach ($params as $item) {
        $req      = [
            'index' => EsIndex,
            'id'    => $item['id'],
            'body'  => [
                'car_name' => $item['car_name'],
            ],
        ];
        $response = $client->create($req);
        print_r($response->asArray());
    }
}

function getData(): void
{
    $client = esClient();

    $params = [
        'index' => EsIndex,
        'size' => 1
    ];

    $params['body']['query']['match']['car_name'] = '小鹏G3 520i 尊享版';

    $response = $client->search($params);

    print_r($response->asArray());
}